# coding=utf-8
# 第一版 2022/3/21 author: ylong52@21cn.com
from http import server
from lib2to3.pgen2 import driver
from urllib.parse import urlparse
from myselenium import *
import sys
from LocalStorage import *
from browsermobproxy import Server
import json

 
#解决占用端口
def kill_process(port):
    # os.system('taskkill /im chromedriver.exe /F')
    # os.system('taskkill /im chrome.exe /F')

    ret = os.popen("netstat -nao|findstr '"+str(port)+"'")    
    #注意解码方式和cmd要相同，即为"gbk"，否则输出乱码
    str_list = ret.read() 
    time.sleep(0.5)
    ret_list = re.split('',str_list)
    try:
        process_pid = list(ret_list[0].split())[-1]
        os.popen('taskkill /pid ' + str(process_pid) + ' /F')
        print("端口已被释放")
    except:
        #print("端口未被使用")
        return True

 
#主程序
def main():
    kill_process(8090);
    # getGoodINIUrl()  
    dict={'port':8090} #browsermob-proxy端口
    #server = Server(r'.\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat') 
    sserver = Server(r".\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat",options=dict)
    
    
    sserver.start()
    proxy = sserver.create_proxy()    
    chrome_options2 = Options()
    
    
    # chrome_options2.add_argument('--headless') #有这行，表示不显示浏览器

    chrome_options2.add_argument('--disable-gpu')
    chrome_options2.add_argument('--ignore-certificate-errors')
    chrome_options2.add_argument('--ignore-ssl-errors')
    chrome_options2.add_argument('--proxy-server={0}'.format(proxy.proxy))

    prefs = {"profile.managed_default_content_settings.images": 2}
    chrome_options2.add_experimental_option("prefs", prefs)

    driver = webdriver.Chrome(options=chrome_options2)
    driver.set_window_size(500,800)
    
      
    driver.get('https://artmeta.cn/')
    time.sleep(1)

    loginAccount(driver,proxy)
    # if retStatus== False:
    #     sserver.stop()
    #     driver.quit()
    #     return False
    # else:
    #     time.sleep(300)
    time.sleep(300)
    
#读ini文件  
# def getGoodINIUrl():
#     cfg1 = "config.ini"
#     conf = configparser.ConfigParser()
#     conf.read(cfg1, encoding="utf-8-sig")

#     #读取ini文件中的内容
#     # price = conf.get("goods", "price")
#     # goodsurl = conf.get("goods", "goodsurl")    



def loginAccount(driver,proxy):
     
    storage = LocalStorage(driver)
    
    storage["truename"] = '刘洋'
    storage["UserLoginToken"] = '{"type":"object","data":{"AccessTokenKey":"510bf47c-3a98-4091-851a-b5503d45b62c","AccessTokenExpiresTime":1647844560,"RefreshTokenKey":"68c3de79-0766-4afa-8a38-7198b585f9cb","RefreshTokenExpiresTime":1647844560}}'
    storage["userinfo"] = '{"type":"object","data":{"UserId":208699,"UserName":"adc","AvatarUrl":"https://images.cang.com/CommImg/comm/nft_avatar_default.png","Phone":"18694064658","Nickname":null,"CreateTime":"2022-02-28T00:37:37","UserStatus":1,"IsSetTradePassword":1,"IsAuthRealName":1,"TrueName":"刘洋","IsAddBank":0,"IsAuthEmail":0,"EmailAddress":null,"IsArtist":0}}'
    storage["UserId"] = '{"type":"number","data":208699}'
    
    print('start......')
    # time.sleep(200)

    driver.get('https://artmeta.cn/pages/usercenter/usercenter')
    #_txt = valclass(driver, 'user-id')
    time.sleep(1)
    if(storage.get("truename")==None):
        print('帐号登录登录失败!!!!!')
    else:
        print('帐号登录成功 >>>')   
     
   
    # if _txt:
    #    _txt2 = valclass(driver, 'user-id') 
    #    print('个人中心')
     
    # else:
    
    #     print('登录失败')



#找到转售市场
def derivativedetail(driver,proxy):
    goods_id = 131138 #指定商品
    global goodsurl

    # url = 'https://artmeta.cn/pages/derivativedetail/derivativedetail?id=' + str(goods_id)    
    #proxy.new_har(url)
    proxy.new_har("huaruntong", options={'captureHeaders': True, 'captureContent': True})
    driver.get(goodsurl)
    time.sleep(1)
    tapid(driver,'u-tab-item-1')   #换到tab页面
    time.sleep(5)
    for i in range(5):
        print(f'第{i+1}页>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        item_id2 = getHarUrl(driver,proxy.har)
         
        #mouse滚轮向下翻页  
        js="window.scrollTo(0,document.body.scrollHeight)"
        driver.execute_script(js)
        time.sleep(3)

     
    # element1 = WebDriverWait(driver, 15).until(
    #         EC.presence_of_element_located((By.CLASS_NAME, "u-tab-item-1"))
    #     )
    
    # element1.send_keys(Keys.PAGE_DOWN)    
    print('end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
    # driver.quit()

#取包
def getHarUrl(driver,result):
    _filter_price = 1700;  #最低的价格
    for entry in result['log']['entries']:
        _url = entry['request']['url']
        if "https://api.artmeta.cn/api.ashx" in _url:
            print(">>>>>>>>>>"+_url+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            _response = entry['response']
            _content = _response['content']
            #print(_url)
            #print(_content)
            if "GoodsId" in json.dumps(_content):
                dataout(driver,_content,_filter_price)
            #print(entry)
            print("<<<< url end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
 

   
##分析接口数据
def dataout(driver,data,_filter_price):
    #json.dumps将python对象格式化成json字符（将dict转化成str）
    #json.loads将json字符串解码成python对象（将str转化成dict）
    _dict = json.loads(data['text'])
    _datalist = _dict.get('Data')['Data'] #datalist是dict类型 
    _find_num = 0;
    for i in _datalist:       
        #print("id:"+str(i['GoodsId'])+",name:"+i['GoodsName']+",price:"+str(i['GoodsPrice'])+"\n")
        if (to_int(i['GoodsPrice'])<=_filter_price):
            print("id:"+str(i['GoodsId'])+",name:"+i['GoodsName']+",price:"+str(i['GoodsPrice'])+"\n")
            worksdetail(driver,i['GoodsId'])
            _find_num +=1
            driver.quit()
            sys.exit()
            break
    if (_find_num==0):
        print("未找到符合条件的商品ID"+str(i['GoodsId']))
    return False
    
  
#购买页面
def worksdetail(driver,item_id):
 
    url = "https://artmeta.cn/pages/worksdetail/worksdetail?id="+str(item_id)
    driver.get(url)
    element = WebDriverWait(driver,3,0.3).until(
        EC.presence_of_element_located((By.CLASS_NAME, "works-offer-purchase"))
    )
    element.click()
    element2 = WebDriverWait(driver,3,0.1).until(
        EC.presence_of_element_located((By.CLASS_NAME, "next"))
    )
    time.sleep(0.3)
    element2.click()
    #点“购买”按钮,默认选的支付宝
    try:
        element3 = WebDriverWait(driver,3,0.1).until(
            EC.presence_of_element_located((By.CLASS_NAME, "pay"))
        )
        time.sleep(0.3)
        element3.click()
    except:    
        if "worksdetail" in driver.current_url:
            print("\n\n￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣")
            print("支付失败！！！！！！,估计是账户被锁12小时。手工去查看个人中心 !!!!!\n\n")
            driver.quit()
            sys.exit()             
        if "cashier" in driver.current_url:
            print("\n\n￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣")
            print("已经点了立即支付，请去个人中心付款\n")
            print("⊙▽⊙ ⊙▽⊙ ⊙▽⊙ \n\n")
            driver.quit()
            sys.exit() 
        
        
    

#-------------------- start 
main()
 


